package com.ys.ylideas.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.ys.ylideas.YlIdeasApplication;
import com.ys.ylideas.entity.BaiUserContact;
import com.ys.ylideas.entity.IdeaEntity;
import com.ys.ylideas.entity.IdeaHelp;
import com.ys.ylideas.entity.UserEntity;
import com.ys.ylideas.model.Idea;
import com.ys.ylideas.service.AccountService;
import com.ys.ylideas.service.IdeaService;
import com.ys.ylideas.util.CreativeOperation;
import com.ys.ylideas.util.HttpRequest;
import com.ys.ylideas.util.R;
import com.ys.ylideas.util.StringDealUtil;
import com.ys.ylideas.util.TimeUtil;

@RestController
@RequestMapping("/ideaController")
public class YiIdeaController {

	@Autowired
	private IdeaService ideasService;
	
	@Autowired
	private AccountService accountService;
	private int num=7;
	private static final Logger logger = LoggerFactory.getLogger(YlIdeasApplication.class);
	private static final int APP_ID = 2;
	/**
	 * 对创意的操作
	 * @param idea
	 * @return
	 */
	@RequestMapping(value="/ideaOperation")
	public R ideaOperation(@RequestBody Idea idea){
		IdeaEntity ideasEntity = new IdeaEntity();
		List<UserEntity> userEntities = accountService.checkAccount(idea.getUserId());
		String refresh_token = accountService.getUserToken(userEntities.get(0).getUserId());
		List<String> list = HttpRequest.getAccessToken(refresh_token);
		String access_token = list.get(0);
		if (access_token == null) {
			return R.error("can't get access token");
		}
		refresh_token = list.get(1);
		userEntities.get(0).setRefreshToken(refresh_token);
		accountService.update(userEntities.get(0));
		ideasEntity.setIdeaTitle(idea.getIdeaTitle().replaceAll("[\\>\\<\\ ]", ""));
		ideasEntity.setIdeaDesOne(idea.getIdeaDesOne().replaceAll("[\\>\\<\\ ]", ""));
		ideasEntity.setIdeaDesTwo(idea.getIdeaDesTwo().replaceAll("[\\>\\<\\ ]", ""));
		ideasEntity.setDisplayUrl(idea.getDisplayUrl().replaceAll("[\\>\\<\\ ]", ""));
		ideasEntity.setVisitUrl(idea.getVisitUrl().replaceAll("[\\>\\<\\ ]", ""));
		ideasEntity.setMobileDisplayUrl(idea.getDisplayUrl().replaceAll("[\\>\\<\\ ]", ""));
		ideasEntity.setMobileVisitUrl(idea.getVisitUrl().replaceAll("[\\>\\<\\ ]", ""));
		ideasEntity.setAdgroupId(idea.getAdgroupId());

		if (idea.getCode() == 0) {
			ideasEntity.setAccountId(userEntities.get(0).getId());
			ideasService.save(ideasEntity);
			return R.ok();
		} else if (idea.getCode() == 1) {
			if (idea.getCreativeId()!=0) {
				ideasEntity.setCreativeId(idea.getCreativeId());
				Map<String, Object> map = HttpRequest.updateCreate(access_token, ideasEntity);
				Map<String, String> map1 = CreativeOperation.addOrUpdate(map, 1);
				if (map1.get("msg")!=null&&map1.get("msg").equals("success")) {
					ideasEntity.setId(idea.getId());
					ideasService.update(ideasEntity);
					return R.ok();
				} else {
					if (map1.get("msg").equals("failure")) {
						return R.error(410, map.get("msg").toString());
					} else {
						return R.error(410, map1.get("msg"));
					}
				}
			}else{
				Map<String, Object> map = HttpRequest.addCreate(access_token, ideasEntity);
				Map<String, String> map1 = CreativeOperation.addOrUpdate(map, 0);
				if (map1.get("creativeId")!=null&&map1.get("creativeId")!="") {
					ideasEntity.setId(idea.getId());
					ideasEntity.setCreativeId(Long.parseLong(map1.get("creativeId").toString()));
					ideasService.update(ideasEntity);
					return R.ok();
				} else {
					if (map1.get("msg").equals("failure")) {
						return R.error(410, map.get("msg").toString());
					} else {
						return R.error(410, map1.get("msg"));
					}
				}
			}
		}else if (idea.getCode() == 2) {
			Map<String, Object> map = HttpRequest.addCreate(access_token, ideasEntity);
			Map<String, String> map1 = CreativeOperation.addOrUpdate(map, 0);
			if (map1.get("creativeId")!=null&&map1.get("creativeId")!="") {
				ideasEntity.setAccountId(userEntities.get(0).getId());
				ideasEntity.setCreativeId(Long.parseLong(map1.get("creativeId").toString()));
				ideasService.save(ideasEntity);
				return R.ok();
			} else {
				if (map1.get("msg").equals("failure")) {
					return R.error(410, map.get("msg").toString());
				} else {
					return R.error(410, map1.get("msg"));
				}
				
			}
		}
		return R.error(410, "未知错误");
	}
	
	/**
	 * 修改创意
	 * @param idea
	 * @return
	 */
	@RequestMapping("/update")
	public R update(@RequestBody IdeaEntity idea){
		IdeaEntity ideasEntity = new IdeaEntity();
		ideasEntity.setId(idea.getId());
		ideasEntity.setIdeaTitle(idea.getIdeaTitle().replaceAll("[\\>\\<\\ ]", ""));
		ideasEntity.setIdeaDesOne(idea.getIdeaDesOne().replaceAll("[\\>\\<\\ ]", ""));
		ideasEntity.setIdeaDesTwo(idea.getIdeaDesTwo().replaceAll("[\\>\\<\\ ]", ""));
		ideasEntity.setDisplayUrl(idea.getDisplayUrl().replaceAll("[\\>\\<\\ ]", ""));
		ideasEntity.setVisitUrl(idea.getVisitUrl().replaceAll("[\\>\\<\\ ]", ""));
		ideasService.update(ideasEntity);
		return R.ok();
	}
	
	@RequestMapping("/delete")
	public R delete(@RequestParam("id") long id){
		ideasService.delete(id);
		return R.ok();
	}
	
	/**
	 * 删除多条创意
	 * @param ids
	 * @return
	 */
	@RequestMapping("/deleteMore")
	public R deleteMore(@RequestBody Map<String, Object> params){
		Integer[] ids = null;
		int userId = 0;
		int requestType = 1;
		if(params.get("ids")!=null){
			List idList =  (List) params.get("ids");
			ids = new Integer[idList.size()];
			for(int i=0;i<idList.size();i++){
				ids[i] = Integer.parseInt(idList.get(i).toString());
			}
		}
		if (params.get("userId")!=null) {
			userId = Integer.parseInt(params.get("userId").toString());
		}
		if (params.get("requestType")!=null) {
			requestType = Integer.parseInt(params.get("requestType").toString());
		}
		List<UserEntity> userEntities = accountService.checkAccount(userId);
		String refresh_token = accountService.getUserToken(userEntities.get(0).getUserId());
		List<String> list = HttpRequest.getAccessToken(refresh_token);
		String access_token = list.get(0);
		if (access_token == null) {
			return R.error("can't get access token");
		}
		refresh_token = list.get(1);
		userEntities.get(0).setRefreshToken(refresh_token);
		accountService.update(userEntities.get(0));
		if (requestType == 0) {
			ideasService.deleteBatch(ids);
			return R.ok();
		}else if (requestType == 1) {
			Long[] creativeIdArray = ideasService.queryForIdeaListById(ids);
			Map<String, Object> map = HttpRequest.deleteCreate(access_token, creativeIdArray);
			Map<String, Object> map1 = new HashMap<>();
			if (map!=null) {
				if (map.get("status").equals("failure")) {
					Properties prop = new Properties();     
			        try{
			            //读取属性文件a.properties
			        	prop.load(YiIdeaController.class.getClassLoader().getResourceAsStream("error_code.properties"));
			            Iterator<String> it=prop.stringPropertyNames().iterator();
			            while(it.hasNext()){
			            	String key = it.next();
			            	logger.debug(key+"===="+map.get("code").toString());
			                if (key.equals(map.get("code").toString())) {
			                	logger.debug(map.get("code").toString());
			                	map1.put("msg",prop.getProperty(key));
							}
			            }
			        }catch(Exception e){
			        	map1.put("msg",e.toString());
			        }
			        ideasService.deleteBatch(ids);
			        return R.error(410,map1.get("msg").toString());
				}else if(map.get("status").equals("success")){
					logger.debug("当前状态："+map.get("status"));
					ideasService.deleteBatch(ids);
					return R.ok();
				}else{
					Properties prop = new Properties();     
			        try{
			            //读取属性文件a.properties
			        	prop.load(YiIdeaController.class.getClassLoader().getResourceAsStream("error_code.properties"));
			            Iterator<String> it=prop.stringPropertyNames().iterator();
			            while(it.hasNext()){
			            	String key = it.next();
			            	logger.debug(key+"===="+map.get("code").toString());
			                if (key.equals(map.get("code").toString())) {
			                	logger.debug(map.get("code").toString());
			                	map1.put("msg",prop.getProperty(key));
							}
			            }
			        }catch(Exception e){
			        	map1.put("msg",e.toString());
			        }
//			        List<Integer> failedList = (List<Integer>) map.get("failCode");
//			        List<Integer> successList = (List<Integer>) map.get("suCode");
//			        Integer[] failedArray = new Integer[failedList.size()];
//			        Integer[] successArray = new Integer[successList.size()];
//			        successList.toArray(successArray);
//			        for(int i=0;i<successList.size();i++){
//			        	successArray[i] = ids[successList.get(i)];
//			        }
//			        map1.put("failedArray", failedArray);
			        ideasService.deleteBatch(ids);
			        return R.error(410, map1.get("msg").toString());
				}
			}
		}
		return R.error(410, "未知错误");
	}
	
	
	@RequestMapping(value="/getUserIdeaList")
	public R getUserIdeaList(@RequestParam(value="identifier",required=false) int identifier,@RequestParam(value="requestType") int type,@RequestParam(value="page",required=false) String page){
		List<IdeaEntity> ideasList = new ArrayList<>();
		List<UserEntity> userList = accountService.checkAccount(identifier);
		Map<String, Object> map = new HashMap<>();
		Map<String,Object> map2 = new HashMap<>();
		int allCount,pageCount=0;
		if (page==null||page=="") {
			page ="1";
		}
		if (type == 1) {
			map.put("accountId", userList.get(0).getId());
			map.put("type", type);
			allCount = ideasService.queryForIdeaList(map).size();
			map.put("index", (Integer.parseInt(page)-1)*num);
			map.put("num",num);
			ideasList = ideasService.queryForIdeaList(map);
			if(allCount%num==0)
				pageCount = allCount/num;
			else
				pageCount = allCount/num+1;
			
			map2.put("userIdeaList", ideasList);
			map2.put("pageCount",pageCount);
			map2.put("page",page);
		}else if(type==0){
			map.put("accountId", userList.get(0).getId());
			map.put("type", type);
			allCount = ideasService.queryForIdeaList(map).size();
			map.put("index", (Integer.parseInt(page)-1)*num);
			map.put("num",num);
			ideasList = ideasService.queryForIdeaList(map);
			if(allCount%num==0)
				pageCount = allCount/num;
			else
				pageCount = allCount/num+1;
			
			map2.put("userIdeaList", ideasList);
			map2.put("pageCount",pageCount);
			map2.put("page",page);
		}
		
		return R.ok(map2);
		
	}
	
	
	/**
	 * 
	 * 导出创意格式的csv文件
	 * 
	 */
	@RequestMapping(value = "/exportCreativeCSV")
	@ResponseBody
	public void exportCreativeCSV(HttpServletRequest req,HttpServletResponse resp) {
		String ids = req.getParameter("fileName");
		String[] idArray = ids.split(",");
		List<String> idsList = new ArrayList<>();
		for(int i=0;i<idArray.length;i++){
			idsList.add(idArray[i]);
		}

		String result = ideasService.exportCreateCreativeCSV(idsList);
		try {
			String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
			
			String filename = "-创意-"+date;
			resp.setContentType("application/csv;charset=UTF-8");
			resp.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(filename, "UTF-8") +".csv");
			OutputStream out = resp.getOutputStream();
			OutputStreamWriter osw = new OutputStreamWriter(resp.getOutputStream(), "UTF-8");
			osw.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF })); // 导出csv文件需添加bom头信息
			osw.write(result);
			osw.flush();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	}
	
	/** 获取用户搜索的创意 **/
	@PostMapping(value="/getSearchIdea")
	public R getSearchIdea(@RequestParam("keyword") String kw){
		String[] kws = kw.split(",");
		List<String> keywords = new ArrayList<>();
		for(int i = 0;i<kws.length;i++){
			keywords.add(kws[i].toString());
		}		
		
		
		// 有搜索结果的查询词
		List<String> hasResultWords = new ArrayList<>();
		
		List<IdeaHelp> org = new ArrayList<>();
		for(int a=0;a<keywords.size();a++){
			List<IdeaHelp> idea = ideasService.queryIdea(keywords.get(a));
			org.addAll(idea);
			if(idea.size()!=0){
				hasResultWords.add(keywords.get(a));
			}
		}
		
		int totalpage = 0;		
		int pageSize = 5;
		
		if(hasResultWords.size()%pageSize!=0){
			totalpage = hasResultWords.size()/pageSize+1;
		}else{
			if(!hasResultWords.isEmpty()){
				totalpage = hasResultWords.size()/pageSize;
			}else{
				totalpage = 1;
			}
			
		}
		
		
		for(int b=0;b<org.size();b++){
			String title = org.get(b).getOriginalityTitle();
			String desc_one = org.get(b).getOriginalityDescribeOne();
			String desc_two = org.get(b).getOriginalityDescribeTwo();
			String ky = hasResultWords.get(b);
			org.get(b).setOriginalityTitle(StringDealUtil.highLightWord(title, ky));
			org.get(b).setOriginalityDescribeOne(StringDealUtil.highLightWord(desc_one, ky));
			org.get(b).setOriginalityDescribeTwo(StringDealUtil.highLightWord(desc_two, ky));
		}
		
		Map<String,Object> map = new HashMap<>();
		map.put("totalPage", totalpage);
		map.put("searchResult", org);
		return R.ok(map);
	}
	
	@PostMapping(value="/getUnitIdea")
	public R getUnitIdea(@RequestParam("keyword") String kw,@RequestParam(value="page",required=false) String page,HttpSession httpSession){
		String[] kws = kw.split(",");
		List<String> keywords = new ArrayList<>();
		List<IdeaHelp> org = new ArrayList<>();
		List<IdeaHelp> searchResultList = new ArrayList<>();
		Map<String, Object> map = new HashMap<>();
		int pageCount=0,allCount=0;
		for(int i = 0;i<kws.length;i++){
			keywords.add(kws[i].toString());
		}
		if (page==null||page=="") {
			page ="1";
		}
		if (keywords.size()==1) {
			String keyword = keywords.get(0);
			List<IdeaHelp> idea = ideasService.queryIdea(keyword);
			if(idea.size()!=0){
				for(int b=0;b<idea.size();b++){	
					String title = idea.get(b).getOriginalityTitle();
					String desc_one = idea.get(b).getOriginalityDescribeOne();
					String desc_two = idea.get(b).getOriginalityDescribeTwo();
					idea.get(b).setOriginalityTitle(StringDealUtil.highLightWord(title, keyword));
					idea.get(b).setOriginalityDescribeOne(StringDealUtil.highLightWord(desc_one, keyword));
					idea.get(b).setOriginalityDescribeTwo(StringDealUtil.highLightWord(desc_two, keyword));
				}
				org.addAll(idea);
				if (org.size()>=1) {
					pageCount = 1;
				}else{
					page = 0+"";
				}
			}
			map.put("unitIdeaList", org);
			map.put("pageCount",pageCount);
			map.put("page",page);
			return R.ok(map);
		}else if (keywords.size()>=2) {
			for(int a=0;a<keywords.size();a++){
				String keyword = keywords.get(a);
				List<IdeaHelp> idea = ideasService.queryUnitIdea(keyword);
				if(idea.size()!=0){
					for(int b=0;b<idea.size();b++){	
						String title = idea.get(b).getOriginalityTitle();
						String desc_one = idea.get(b).getOriginalityDescribeOne();
						String desc_two = idea.get(b).getOriginalityDescribeTwo();
						idea.get(b).setOriginalityTitle(StringDealUtil.highLightWord(title, keyword));
						idea.get(b).setOriginalityDescribeOne(StringDealUtil.highLightWord(desc_one, keyword));
						idea.get(b).setOriginalityDescribeTwo(StringDealUtil.highLightWord(desc_two, keyword));
					}
					org.addAll(idea);
				}
			}
			allCount = org.size();
			if (allCount == 0) {
				page=0+"";
			}else{
				if(allCount%num==0)
					pageCount = allCount/num;
				else
					pageCount = allCount/num+1;
				for(int i=0;i<allCount&&i<=6;i++){
					searchResultList.add(org.get(i));
				}
				httpSession.setAttribute("unitIdeaList", org);
			}
			map.put("unitIdeaList", searchResultList);
			map.put("pageCount",pageCount);
			map.put("page",page);
			return R.ok(map);
		}
		map.put("unitIdeaList", searchResultList);
		map.put("pageCount",0);
		map.put("page",0);
		return R.ok(map);
	}

	
	/** 点击其他页查看创意*/
	@PostMapping("/getOtherPageIdea")
	public R getOtherPageIdea(@RequestParam("keyword") String kw,@RequestParam("page") int page){
		String[] kws = kw.split(",");
		List<String> keywords = new ArrayList<>();
		for(int i = 0;i<kws.length;i++){
			keywords.add(kws[i].toString());
		}
		
		int pageSize = 5;
		int total = keywords.size();
		int totalPage = 0;
		
		if(total%pageSize!=0){
			totalPage = total/pageSize+1;
		}else{
			totalPage = total/pageSize;
		}
		
		if(page == totalPage){
			keywords = keywords.subList((page-1)*pageSize, keywords.size());
		}else{
			keywords = keywords.subList((page-1)*pageSize, page*pageSize);
		}
		
		List<IdeaHelp> org = new ArrayList<>();
		for(int a=0;a<keywords.size();a++){
			List<IdeaHelp> idea = ideasService.queryIdea(keywords.get(a));
			org.addAll(idea);
		}
		
		for(int b=0;b<org.size();b++){
			String title = org.get(b).getOriginalityTitle();
			String desc_one = org.get(b).getOriginalityDescribeOne();
			String desc_two = org.get(b).getOriginalityDescribeTwo();
			String ky = keywords.get(b);
			org.get(b).setOriginalityTitle(StringDealUtil.highLightWord(title, ky));
			org.get(b).setOriginalityDescribeOne(StringDealUtil.highLightWord(desc_one, ky));
			org.get(b).setOriginalityDescribeTwo(StringDealUtil.highLightWord(desc_two, ky));
		}
		return R.ok().put("searchResult", org);
	}
	
	@RequestMapping("/getIdeaSession")
	public R getIdeaSession(@RequestBody Map<String,Object> jsonData,HttpSession request) {
		int code = -1;
		int page = 1;
		int allCount,pageCount;
		List<IdeaHelp> unitIdeaList1 = new ArrayList<>();
		Map<String, Object> map = new HashMap<>();
		if(jsonData.get("code")!=null){
			code = Integer.parseInt(jsonData.get("code").toString());
		}
		if (jsonData.get("page")!=null) {
			page = Integer.parseInt(jsonData.get("page").toString());
		}
		if (code == 0) {
			List<IdeaHelp> unitIdeaList2 = (List<IdeaHelp>) request.getAttribute("unitIdeaList");
			int firstNum,endNum;
			firstNum = (page-1)*num;
			endNum = firstNum +6;
			if (unitIdeaList2.size()>=1) {
				for(int i=firstNum;i<unitIdeaList2.size()&&i<=endNum;i++){
					unitIdeaList1.add(unitIdeaList2.get(i));
				}
				allCount = unitIdeaList2.size();
				if(allCount%num==0)
					pageCount = allCount/num;
				else
					pageCount = allCount/num+1;
				map.put("unitIdeaList", unitIdeaList1);
				map.put("pageCount",pageCount);
				map.put("page",page);
				return R.ok(map);
			}else{
				return R.ok(map);
			}
		}
		return R.ok(map);
	}

	@RequestMapping(value = "/saveForService")
	public R saveForService(@RequestBody BaiUserContact params, HttpSession request) {
		if (request.getAttribute("User") == null) {
			return R.error("session is null");
		} else {
		    UserEntity userMsg = new UserEntity();
		    userMsg = (UserEntity)request.getAttribute("User");
		    Long userId = userMsg.getUserId();
		    UserEntity user = new UserEntity();
		    user = accountService.checkAccount(userId).get(0);
			BaiUserContact e = new BaiUserContact();
			e.setCompany_name(params.getCompany_name());
			e.setPhone_number(params.getPhone_number());
			e.setAppId(APP_ID);
			e.setUserId(userId);
			e.setCreateTime(TimeUtil.getTime());
			e.setVisitTime(user.getRecentTime());
			accountService.saveForService(e);
			return R.ok();
		}
	}

}
